package base_middleware

import (
	"fmt"
	oc_types "oc_saas/internal/types"
	"os"
	"runtime"

	"github.com/gin-gonic/gin"
)

var env = os.Getenv("MODE")

// 自定义错误处理
func CustomRecovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				var stackBucket []string
				if env == "dev" {
					stackBucket = stack(3)
				}
				var resBody = &oc_types.ResBody{
					Code: oc_types.FAIL,
					Msg:  "",
					Trace: &oc_types.Trace{
						Stack: stackBucket,
						Error: "",
					},
				}
				if customErr, ok := err.(*oc_types.CustomError); ok {
					resBody.Msg = customErr.Msg
					resBody.Trace.Error = customErr.Error
				} else {
					resBody.Msg = fmt.Sprintf("%v", err)
					resBody.Trace.Error = fmt.Sprintf("%v", err)
				}
				oc_types.Response(200, *resBody, c)
			}
		}()
		c.Next()
	}
}

func stack(skip int) []string {
	var errStr []string
	for i := skip; ; i++ { // Skip the expected number of frames
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}
		errStr = append(errStr, fmt.Sprintf("%s:%d (0x%x)\n", file, line, pc))
	}
	return errStr
}
